package com.jhx.common.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Paint;
import android.os.Build;
import android.os.IBinder;
import android.os.Parcel;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 屏幕显示工具类
 *
 * @author 罗文忠
 * @version 1.0
 * @date 2013-04-02
 */
public class DisplayUtil {

    /**
     * 获取通知栏告诉.
     *
     * @param context 上下文环境.
     * @return 通知栏高度.
     * @version 1.0
     * @createTime 2013-9-15,下午2:29:29
     * @updateTime 2013-9-15,下午2:29:29
     * @createAuthor paladin
     * @updateAuthor paladin
     * @updateInfo
     */
    public static int getStatusBarHeight(Context context) {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, statusBarHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return statusBarHeight;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     *
     * @author 罗文忠
     * @date 2013-04-02
     * @version 1.0
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     *
     * @author 罗文忠
     * @date 2013-04-02
     * @version 1.0
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue
     * @return
     */
    public static int px2sp(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (spValue * scale + 0.5f);
    }

    /**
     * dip转sp
     * @param dpValue
     * @return
     */
    public static int dip2sp(Context context, float dpValue) {
        int pxValue = dip2px(context, dpValue);
        return px2sp(context, pxValue);
    }

    /**
     * 获取屏幕宽度
     *
     * @param context
     * @return
     * @version 1.0
     * @createTime 2014年3月18日 下午12:54:02
     * @updateTime 2014年3月18日 下午12:54:02
     * @createAuthor liuyue
     * @updateAuthor liuyue
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    public static int getScreenWidth(Context context) {
        int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
        return screenWidth;
    }

    /**
     * 获取屏幕高度有状态栏的高度
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        int screenHeight = context.getResources().getDisplayMetrics().heightPixels;
        return screenHeight;
    }

    /**
     * 得到屏幕除去静态状态栏的显示高度(px)
     *
     * @param context
     * @return
     * @version 1.0
     * @createTime 2015年5月21日, 上午9:46:54
     * @updateTime 2015年5月21日, 上午9:46:54
     * @createAuthor yanzhong
     * @updateAuthor
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    public static int getShowHeight(Context context) {
        int screenHeight = context.getResources().getDisplayMetrics().heightPixels;
        int showHeight = screenHeight - getStatusBarHeight(context);
        return showHeight;
    }


    /**
     * 根据比例设置控件的宽高
     *
     * @param context 上下文
     * @version 1.0
     * @createTime 2015年3月6日, 下午8:00:24
     * @updateTime 2015年3月6日, 下午8:00:24
     * @createAuthor chencong
     * @updateAuthor chencong
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    public static void setViewWH(Context context, View view, float l) {
        int screenWidth = DisplayUtil.getScreenWidth(context);
        int height = (int) (screenWidth / l);
        view.setLayoutParams(new LayoutParams(screenWidth, height));
    }

    /**
     * 根据比例设置控件的宽高(迪讯好友资料页面专用)
     *
     * @param context 上下文
     * @version 1.0
     * @createTime 2015年3月6日, 下午8:00:24
     * @updateTime 2015年3月6日, 下午8:00:24
     * @createAuthor chencong
     * @updateAuthor chencong
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    public static void setViewWH_Dixun(Context context, View view, int v, float l) {
        int screenWidth = DisplayUtil.getScreenWidth(context);
        int height = (int) (screenWidth / l);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(screenWidth, height);
        layoutParams.addRule(RelativeLayout.ABOVE, v);
        view.setLayoutParams(new RelativeLayout.LayoutParams(screenWidth, height));

    }

    /**
     * 根据比例设置控件的宽高(引导页)
     *
     * @param context 上下文
     * @version 1.0
     * @createTime 2015年3月6日, 下午8:00:24
     * @updateTime 2015年3月6日, 下午8:00:24
     * @createAuthor chencong
     * @updateAuthor chencong
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    public static void setViewWH_TopL(Context context, View view, float l, float scale) {
        int screenWidth = (int) (DisplayUtil.getScreenWidth(context) * scale);
        int height = (int) (screenWidth / l);
        LayoutParams layoutParams = new LayoutParams(screenWidth, height);
        layoutParams.topMargin = dip2px(context, 75 * scale);
        view.setLayoutParams(layoutParams);
    }

    /**
     * 根据比例设置控件的宽高(引导页)
     *
     * @param context 上下文
     * @version 1.0
     * @createTime 2015年3月6日, 下午8:00:24
     * @updateTime 2015年3月6日, 下午8:00:24
     * @createAuthor chencong
     * @updateAuthor chencong
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    public static void setViewWH_TxtL(Context context, View view, float l, float scale) {
        int screenWidth = (int) (DisplayUtil.getScreenWidth(context) * scale);
        int height = (int) (screenWidth / l);
        LayoutParams layoutParams = new LayoutParams(screenWidth, height);
        layoutParams.topMargin = dip2px(context, 20 * scale);
        view.setLayoutParams(layoutParams);
    }

    /**
     * 根据比例设置控件的宽高（使用在加载也的广告图上面）
     *
     * @param context 上下文
     * @version 1.0
     * @createTime 2015年3月6日, 下午8:00:24
     * @updateTime 2015年3月6日, 下午8:00:24
     * @createAuthor chencong
     * @updateAuthor chencong
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    public static void setViewWH_R(Context context, View view, float l) {
        int screenWidth = DisplayUtil.getScreenWidth(context);
        int height = (int) (screenWidth / l);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(screenWidth, height);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);// 设置控件在地部
        view.setLayoutParams(layoutParams);
    }

    /**
     * 设置控件的长宽
     *  @param context
     * @param view 要设置的控件
     * @param l 宽高比例
     * @param count 拆分个数
     * @param length 需要减去的长度
     */
    public static LayoutParams setViewWH_L(Context context, View view, float l, int count, int length) {
        int screenWidth = DisplayUtil.getScreenWidth(context);
        int width = (screenWidth - dip2px(context, length)) / count;
        int height = (int) (width / l);
        LayoutParams layoutParams = new LayoutParams(width, height);
        view.setLayoutParams(layoutParams);
        return layoutParams;
    }

    /**
     * 设置控件的长宽
     *
     * @param context
     */
    public static void setViewWH_R(Context context, View view, float l, int count, int length) {
        int screenWidth = DisplayUtil.getScreenWidth(context);
        int width = screenWidth / count - dip2px(context, length);
        int height = (int) (width / l);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(width, height);
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        view.setLayoutParams(layoutParams);
    }

    /**
     * 设置控件的长宽
     *
     */
    public static void setViewWH_AbsListView(Context context, View view, float l, int count, int length) {
        int screenWidth = DisplayUtil.getScreenWidth(context);
        int width = screenWidth / count - dip2px(context, length);
        int height = (int) (width / l);
        AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(width, height);
        view.setLayoutParams(layoutParams);
    }

    public static void setLinLayoutW_H(Context context, View view, float l) {
        int screenWidth = DisplayUtil.getScreenWidth(context);
        int height = (int) (screenWidth / l);
        LayoutParams layoutParams = new LayoutParams(screenWidth, height);
        view.setLayoutParams(layoutParams);
    }

    /**
     * 显示/隐藏 软键盘
     *
     * @param context
     * @version 1.0
     * @createTime 2015年3月8日, 上午9:36:37
     * @updateTime 2015年3月8日, 上午9:36:37
     * @createAuthor chencong
     * @updateAuthor chencong
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    public static void showInput(boolean show, Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        View currentFocus = ((Activity) context).getCurrentFocus();
        if (currentFocus != null) {
            IBinder applicationWindowToken = currentFocus.getApplicationWindowToken();
            if (show) {
                if (applicationWindowToken != null) {
                    imm.showSoftInputFromInputMethod(applicationWindowToken, 0);
                }
            } else {
                if (applicationWindowToken != null) {
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(applicationWindowToken, 0);
                    }
                }
            }
        }
    }

    /**
     * 用于处理textview换行问题
     * 陈聪
     *
     * @return
     */
    public static void toSBC(final TextView txt) {
        txt.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onGlobalLayout() {
                txt.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                final String newText = autoSplitText(txt);
                if (!TextUtils.isEmpty(newText)) {
                    txt.setText(newText);
                }
            }
        });
    }

    public static String autoSplitText(final TextView tv) {
        final String rawText = tv.getText().toString(); //原始文本
        final Paint tvPaint = tv.getPaint(); //paint，包含字体等信息
        final float tvWidth = tv.getWidth() - tv.getPaddingLeft() - tv.getPaddingRight(); //控件可用宽度

        //将原始文本按行拆分
        String[] rawTextLines = rawText.replaceAll("\r", "").split("\n");
        StringBuilder sbNewText = new StringBuilder();
        for (String rawTextLine : rawTextLines) {
            if (tvPaint.measureText(rawTextLine) <= tvWidth) {
                //如果整行宽度在控件可用宽度之内，就不处理了
                sbNewText.append(rawTextLine);
            } else {
                //如果整行宽度超过控件可用宽度，则按字符测量，在超过可用宽度的前一个字符处手动换行
                float lineWidth = 0;
                for (int cnt = 0; cnt != rawTextLine.length(); ++cnt) {
                    char ch = rawTextLine.charAt(cnt);
                    lineWidth += tvPaint.measureText(String.valueOf(ch));
                    if (lineWidth <= tvWidth) {
                        sbNewText.append(ch);
                    } else {
                        sbNewText.append("\n");
                        lineWidth = 0;
                        --cnt;
                    }
                }
            }
            sbNewText.append("\n");
        }

        //把结尾多余的\n去掉
        if (!rawText.endsWith("\n")) {
            sbNewText.deleteCharAt(sbNewText.length() - 1);
        }

        return sbNewText.toString();
    }

    /**
     * 设置文本中间变色
     * cc
     */
    public static void setTxtMidColor(Context context, TextView txtview, String txt, String line, int color) {
        SpannableString s = new SpannableString(line);
        // 将名字转换为蓝色
        Pattern p = Pattern.compile(txt);
        Matcher m = p.matcher(s);
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            s.setSpan(new ForegroundColorSpan(context.getResources().getColor(color)), start, end,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        txtview.setText(s);
    }

    /**
     *
     */
    public static void setTxtSizeLeftOrRight(TextView txtview, String mid, String txt, int size, int type) {
        String line = "";
        int start = 0;
        int end = 0;
        if (type == 1) {
            line = mid + txt;
            start = mid.length();
            end = line.length();
        } else if (type == 2) {
            line = txt + mid;
            start = 0;
            end = txt.length();
        }
        SpannableString s = new SpannableString(line);
        // 将名字转换为蓝色
        Parcel p = Parcel.obtain();
        p.writeInt(size);//字体大小
        p.writeInt(8);//是否是dip单位
        p.setDataPosition(0);
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(p);
        s.setSpan(ass, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        txtview.setText(s);
        p.recycle();
    }
}
